package com.example.subject10mvn.controller;


import com.example.subject10mvn.entity.Subject;
import com.example.subject10mvn.responsitory.SubjectResponsitory;
import com.example.subject10mvn.vo.Pagination;
import com.example.subject10mvn.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/subject")
@CrossOrigin
public class SubjectController {
    @Autowired
    SubjectResponsitory subjectResponsitory;

    //插入某个题目
    @PostMapping("/")
    public Result<Object> insertOne(@RequestBody Subject subject){
        subjectResponsitory.saveAndFlush(subject);
        return Result.builder().code("200").data(subject).build();
    }

    //删除某个题目
    @DeleteMapping("/{id}")
    public Result<Object> deleteOne(@PathVariable Integer id){
        subjectResponsitory.deleteById(id);
        return Result.builder().code("200").build();
    }

    //更新某个题目
    @PutMapping("/")
    public Result<Object> updateOne(@RequestBody Subject subject){
        subjectResponsitory.save(subject);
        return Result.builder().code("200").build();
    }

    //根据id获取某个题目
    @GetMapping("/{id}")
    public Result<Object> getOne(@PathVariable("id") Integer id){
        Subject subject=subjectResponsitory.getOne(id);
        return Result.builder().code("200").data(subject).build();
    }

    //获取所有题目
    /*
    @Param pagination 与分页相关的信息，pagination的成员变量page必须从0开始，也就是第一页时page=0
    @Param subjectTypeId 查找的分类
     */
    @GetMapping("/")
    public Result<Object> getAll(Pagination pagination,Integer subjectTypeId){
        if(pagination.getPage()==null){
            pagination.setPage(0);
        }
        if(pagination.getLimit()==null){
            pagination.setLimit(10);
        }
        if(subjectTypeId==null){
            subjectTypeId=0;
        }

        //取出分页
        Pageable pageable=PageRequest.of(pagination.getPage(),pagination.getLimit());
        //判断subjectTypeId==0，如果为0查找所有数据，否则查找指定subjectTypeId的数据
        Page<Subject> subjectPage=subjectTypeId==0?subjectResponsitory.findAll (pageable):subjectResponsitory.findBySubjectTypeId(pageable,subjectTypeId);

        Map<String,Object> map=new HashMap();
        pagination.setTotal(subjectPage.getTotalElements());//修改paginatin的总数
        map.put("page",pagination);
        System.out.println(subjectPage);
        map.put("subjects",subjectPage.getContent());
        return Result.builder().code("200").data(map).build();
    }



}
